package com.arcsoft.commonbase.ext

import android.content.Context
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.arcsoft.commonbase.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
import leifu.shapelibrary.ShapeView

/**
 * 优化输入框，可以只设置afterTextChanged回调
 */
fun EditText.afterTextChange(afterTextChanged: (String) -> Unit) {

    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            afterTextChanged.invoke(s.toString())
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}

/**
 * 设置密码是否可见
 */
fun EditText.setPwdVisible(isVisible: Boolean, imageView: ImageView) {
    if (isVisible) {
        //从密码不可见模式变为密码可见模式
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        imageView.setImageResource(R.mipmap.login_ic_eye_on)
    } else {
        //从密码可见模式变为密码不可见模式
        transformationMethod = PasswordTransformationMethod.getInstance()
        imageView.setImageResource(R.mipmap.login_ic_eye_off)
    }
}

fun EditText.setPwdVisible(imageView: ImageView) {
    if (imageView.tag == R.mipmap.login_ic_eye_on) {
        //从密码可见模式变为密码不可见模式
        transformationMethod = PasswordTransformationMethod.getInstance()
        imageView.setImageResource(R.mipmap.login_ic_eye_off)
        imageView.tag = R.mipmap.login_ic_eye_off
    } else {
        //从密码不可见模式变为密码可见模式
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        imageView.setImageResource(R.mipmap.login_ic_eye_on)
        imageView.tag = R.mipmap.login_ic_eye_on
    }
}

/**
 * 获取文本
 */
fun EditText.textString(): String {
    return this.text.toString()
}

/**
 * 获取去除空字符串的文本
 */
fun EditText.textStringTrim(): String {
    return this.textString().trim()
}

/**
 * 文本是否为空
 */
fun EditText.isEmpty(): Boolean {
    return this.textString().isEmpty()
}

fun EditText.checkEmptyToast(message: String): String? {
    val text = this.text.toString()
    if (text.isEmpty()) {
        showShortToast(message)
        return null
    }
    return text
}

/**
 * 去空字符串后文本是否为空
 */
fun EditText.isTrimEmpty(): Boolean {
    return this.textStringTrim().isEmpty()
}


/**
 * Created by wangkai on 2021/01/30 10:31

 * Desc EditText事件搜索监听，使用协程Coroutine的方式实现
 *
 * 参考自：https://juejin.cn/post/6925304772383735822
 */


open class TextChangeCoroutineDebounceListener(val view: EditText, private val delayMillis: Long = 300L, onTextChanged: ((String?) -> Unit)? = null) :
    LifecycleEventObserver {

    //定义一个全局的 StateFlow
    private val _etState by lazy { MutableStateFlow("") }

    init {
        view.context?.getLifecycleOwner()?.also {
            it.lifecycle.addObserver(this)//注册自己到activity或fragment的LifecycleRegistry中
        }.apply {
            this?.lifecycleScope?.launch {
                _etState
                    .debounce(delayMillis) // 限流，500毫秒
                    .collect {
                        // 订阅数据
                        onTextChanged?.invoke(it)
                    }
            }
        }

        view.afterTextChange {
            // 往流里写数据
            _etState.value = it.trim()
        }
    }


    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {

    }
}


fun EditText?.afterTextChangeCoroutineDebounceListener(debounceTimeOutInMills: Long = 300L, afterTextChange: ((String?) -> Unit)? = null) {
    this?.let {
        TextChangeCoroutineDebounceListener(this, debounceTimeOutInMills) {
            afterTextChange?.invoke(it)
        }
    }
}


/**
 * Context 用于返回LifecycleOwner
 */
fun Context?.getLifecycleOwner(): LifecycleOwner? {
    return when (this) {
        is Fragment -> {
            return this
        }

        is LifecycleOwner -> {
            return this
        }

        else -> {
            null
        }
    }
}


fun btnEnable(btnSure: ShapeView, vararg editTexts: EditText) {
    val find = editTexts.toMutableList().find { it.textStringTrim().isNullOrEmpty() }
    if (find == null) {
        btnSure.alpha = 1F
        btnSure.isEnabled = true
    } else {
        btnSure.alpha = 0.4F
        btnSure.isEnabled = false
    }
}
fun btnEnable(btnSure: ShapeView, boolean: Boolean) {

    if (boolean) {
        btnSure.alpha = 1F
        btnSure.isEnabled = true
    } else {
        btnSure.alpha = 0.4F
        btnSure.isEnabled = false
    }
}
fun btnEnable(btnSure: ShapeView, string: String,vararg editTexts: EditText) {
    val find = editTexts.toMutableList().find { it.textStringTrim().isNullOrEmpty() }
    if (find == null&& string.isNotEmpty()) {
        btnSure.alpha = 1F
        btnSure.isEnabled = true
    } else {
        btnSure.alpha = 0.4F
        btnSure.isEnabled = false
    }
}
